package com.xyy.saas.payment.util;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.xyy.saas.payment.adpater.yzh.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * FileName: DingUtil
 * Author:   jiaxiaosong
 * Date:     2020/5/25 6:07 PM
 * History:
 */
@Slf4j
public class AlarmUtil {

    /**
     * 发送text消息
     *
     * @param contents   发送内容  必填
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static void sendMsg(String webChatWebHook, String webChatMobiles, String contents) {
        try {
            //企业微信机器人地址（配置机器人的webhook）
            String dingUrl = webChatWebHook;
            //企业微信机器人消息内容
            String content = contents;
            //组装请求内容
            String reqStr = buildReqStr(webChatMobiles,content);
            //推送消息（http请求）
            String result = HttpUtil.post(dingUrl, reqStr);
            log.info("发送企业微信text消息成功{}", result);
        } catch (Exception e) {
            log.error("发送企业微信text消息报错", e);
            e.printStackTrace();
        }
    }

    /**
     * 组装请求text报文
     *
     * @param content
     * @return
     */
    private static String buildReqStr(String webChatMobiles,String content) {
        //消息内容
        Map<String, Object> contentMap = Maps.newHashMap();
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        contentMap.put("content", content);

        //2.通知具体人的手机号码列表
        if(StringUtils.isNotEmpty(webChatMobiles)){
            String[] mobiles = webChatMobiles.split(",");
            List<String> mobileList = Arrays.asList(mobiles);
            if (CollectionUtils.isNotEmpty(mobileList)) {
                contentMap.put("mentioned_mobile_list", mobileList);
            }
        }else {
            //1.是否通知所有人
            contentMap.put("mentioned_list", "@all");
        }

        reqMap.put("text", contentMap);
        return JSON.toJSONString(reqMap);
    }



}